<?php
class Controller
{
	/* Variables */
	protected $id;
	protected $template;
	protected $children = array();
	protected $data = array();
	protected $output;
	
	/* Functions */
	public function __get($key) {
		return Registry::get($key);
	}
	
	public function __set($key, $value) {
		Registry::set($key, $value);
	}
	
	public function redirect($url)
	{
		header('Location: ' . $url);	
	}
	
	/*public function fetch($url, $data = null)
	{		
		if(file_exists($url))
		{
			try {
				if(isset($data))
					extract($data);
				
				ob_start();

				require(DIR_THEMES.'header.html');
				require(DIR_THEMES.'column_left.html');
				require(DIR_THEMES.'column_right.html');
				require($url);
				require(DIR_THEMES.'footer.html');
				
				$content = ob_get_contents();
	
				ob_end_clean();
					
				return $content;

			}
			catch (Exception $ex)
			{
				echo $ex->getMessage();
				return null;
			}

		}
		else
		{
			echo "File not exist";
			return null;
		}
	}*/
	
	public function fetch($template)
	{		
		$file = DIR_THEMES . $template;
		if(file_exists($file))
		{
			try {
				
				extract($this->data);
				
				ob_start();
				
				require($file);				
				$content = ob_get_contents();
	
				ob_end_clean();
					
				return $content;

			}
			catch (Exception $ex)
			{
				echo $ex->getMessage();
				return null;
			}

		}
		else
		{
			echo "Template file not exist chim";
			echo "::: " . $file;
			return null;
		}
	}
	
	public function load($modelCls)
	{		
		if(!$this->loader->hasClass($modelCls)){
			$this->loader->model($modelCls);
		}				
	}
	
	public function output($content)
	{		
		echo $content;	
	}
	
	public function render($return = false) 
	{
		foreach ($this->children as $child)
		{
			$file = DIR_CONTROLLER.$child.'.php';
			$class = 'Controller' . preg_replace('/[^a-zA-Z0-9]/','',$child);
			if(file_exists($file)){
				require_once($file);
				
				$instance = new $class;
				
				$instance->index();
				
				$this->data[$instance->id] = $instance->output;
			}					
		}
		
		if($return) {
			return $this->fetch($this->template);
		} else {
			$this->output = $this->fetch($this->template);
		}
	}
	
	
	public function isLogined() {
		if(isset($_SESSION['user_session'])) {
			return true;
		}
		
		return false;
	}
	
}
?>